<?php

namespace h5Api\modules\guest\controllers;

use common\components\fast_api\Controller;
use common\datas\Enums;
use h5Api\models\db\Users;

class SiteController extends Controller
{
    /**
     * 首页
     * @desc 首页
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->apiSuccess([
            'index' => 'index',
        ]);
    }

    public function actionSendJoinCode($mobile)
    {
        return $this->apiSuccess();
    }

    /**
     * 注册
     * @desc 注册
     * @param string $mobile 手机号
     * @param string $password 密码
     * @param string $code 验证码
     * @return mixed
     */
    public function actionRegister($mobile, #[SensitiveParamter] $password, $code)
    {
        $user = Users::findOne(['mobile' => $mobile]);
        if ($user) {
            return $this->apiError("用户已存在");
        }
        $user = new Users();
        $user->mobile = $mobile;
        $user->setPassword($password);
        $user->status = Enums::ACTIVE;
        $user->save();
        return $this->apiSuccess();
    }

    /**
     * 登录
     * @desc JWT登录
     * @param string $mobile 手机号
     * @param string $password 密码
     * @return array
     * @return object jwtData 登录信息
     * @return string jwtData.token
     * @return string jwtData.key
     */
    public function actionLogin($mobile, #[SensitiveParamter] $password)
    {
        $user = Users::findOne(['mobile' => $mobile]);
        if (!$user || !$user->validatePassword($password)){
            return $this->apiError("账号或密码错误");
        }
        if ($user->status !== Enums::ACTIVE) {
            return $this->apiError("用户已被封禁");
        }
        $jwtData = $user->generateJwtTokenData();
        return $this->apiSuccess([
            'jwtData' => $jwtData,
        ]);
    }
}